<?php

namespace Itbbn\ThinkphpModelCreater\lib;

use Itbbn\ThinkphpModelCreater\lib\Config;
use think\facade\Db;


class ModelCreator extends Base
{

    public function getVersion(): string
    {
        return Config::instance()->version;
    }

    /**
     * @param $option array  配置，格式参考config.php
     */
    public function __construct(array $option)
    {
        $orgConfig = require __DIR__ . '/../../config.php';
        //将orgConfig合并到option中,但不要覆盖option
        $option["database"] = array_merge($orgConfig["database"], Util::getValueFromArray("database", $option, []));
        $option["app"] = array_merge($orgConfig["app"], Util::getValueFromArray("app", $option, []));

        $dbDefaultConnection = $option["database"]["default"];
        $option["app"]["prefix"] = $option["database"]["connections"][$dbDefaultConnection]["prefix"];
//        print_r($option);
        Config::instance()->setConfig($option["app"]);
        if (Config::instance()->isThinkPhp) {
            Config::instance()->prefix = config("database.connections")[Config::instance()->thinkPhpDbConnection]["prefix"];
        } else {
            //        print_r($option);
            // 数据库配置信息设置（全局有效）
            Db::setConfig($option["database"]);
            Config::instance()->thinkPhpDbConnection = $dbDefaultConnection;


        }
    }

    public function start(): void
    {
        // 从数据库中查询所有的表名
        $tableList = Db::connect(Config::instance()->thinkPhpDbConnection)->query("show tables");
        $tableCount = count($tableList);
        //var_dump($tableCount);
        if (!$tableList) {
            self::writeln("未找到表格");
            return;
        }
        //生成baseModel
        $this->createBaseModel();
        self::writeln("共有" . $tableCount . "张表");
//        print_r($tableList);
        // 遍历查询结果中的每一个表
        foreach ($tableList as $tableIndex => $table) {
//            print_r($tableList);
            // 遍历每个表的键值对，键为表的索引，值为表名
            foreach ($table as $key => $name) {
                // 输出表名到控制台或日志

//                self::writeRepeat($name);
                // 根据表名创建对应的模型
                $this->createBaseTableModel($name);
//                var_dump($key);
                self::echoPercent($tableIndex + 1, $tableCount, $name);
//                usleep(100000);
                // 根据表名创建对应的模型
                $this->createTableModel($name);
            }
        }
        self::writeln("\n生成完成");


    }

    protected function createBaseModel()
    {
        $baseModelPath = Config::instance()->modelDir . "BaseModel.php";
        $tableModelMaker = new TableModelMaker();
        $tableModelMaker->tableName = Config::instance()->baseModel;
        File::write($tableModelMaker->getBaseFilePath(), $tableModelMaker->getBaseModelCode());
    }

    protected function createTableModel($tableName): void
    {
//        self::writeln("=========begein createTableModel===========");
        $tableModelMaker = new TableModelMaker();
        $prefix = Config::instance()->prefix;//找表名前缀配置
        $modelName = str_replace($prefix, "", $tableName);
        $tableNameCamel = $this->snakeToCamel($modelName);
        $tableModelMaker->tableName = $tableNameCamel;
//        self::writeln($tableModelMaker->getCode());
        $modelPath = $tableModelMaker->getFilePath();
        //判断文件是否存在，存在就跳过
        if (file_exists($modelPath)) {
//            self::writeln($modelPath . "文件已存在");
            return;
        }
        File::write($tableModelMaker->getFilePath(), $tableModelMaker->getCode());
//        self::writeln("=======end createTableModel======");
    }

    protected function createBaseTableModel($tableName): void
    {
        //self::writeln("=========begein createBaseTableModel===========");
        $tableModelMaker = new TableModelMaker();

        $prefix = Config::instance()->prefix;//找表名前缀配置
        $modelName = str_replace($prefix, "", $tableName);
        $tableNameCamel = $this->snakeToCamel($modelName);
        $tableModelMaker->tableName = $tableNameCamel;

        //获取mysql表的信息
        $tableInfo = Db::connect(Config::instance()->thinkPhpDbConnection)->query("show table status like '" . $tableName . "'");
        $tableRemark = $tableInfo[0] ? $tableInfo[0]['Comment'] : "";
        $tableModelMaker->tableRemark = $tableRemark;
        //获取mysql表的列信息
        $tableColumnList = Db::connect(Config::instance()->thinkPhpDbConnection)->query("show full columns from " . $tableName);
        $tableModelMaker->columns = $tableColumnList;

        foreach ($tableColumnList as $key => $column) {
            //找主键
            if ($column['Key'] == "PRI") {
                $tableModelMaker->pk = $column['Field'];
            }
            //判断有没有包含软删除
            if (strtolower($column['Field']) == 'delete_time') {
                $tableModelMaker->isSoftDelete = true;
                $tableModelMaker->softDeleteColumn = $column['Field'];
            }
        }

//        self::writeln($tableModelMaker->getBaseCode());
//        self::writeRepeat($tableModelMaker->getBaseFilePath());
        File::write($tableModelMaker->getBaseFilePath(), $tableModelMaker->getBaseCode());


        //self::writeln("=======end createBaseTableModel======");
    }

    private function snakeToCamel($str)
    {
        $words = explode('_', strtolower($str)); // 首先将字符串按下划线分割并全部小写化

        foreach ($words as &$word) {
            $word = ucfirst(trim($word)); // 对每个单词进行首字母大写处理
        }

        return implode('', $words); // 返回连接后的结果

    }
}